package br.com.rapidrest.chain;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import br.com.rapidrest.exception.ChainException;
import br.com.rapidrest.request.RequestScope;
import br.com.rapidrest.util.RequestScopeBuilder;

public class RequestScopeCommand implements Command {

	public static final String START_PAGE_ATTRIBUTE = "rapidRest.start.page";

	@Override
	public void execute(Chain chain) throws ChainException {
		BasicChainContext context = (BasicChainContext) chain.getContext();
		HttpServletRequest request = context.getRequest();
		String contextPath = request.getContextPath();
		String requestURI = request.getRequestURI();
		requestURI = requestURI.replace(contextPath, "");
		if (requestURI.equals("/")) {
			String startPage = request.getSession().getServletContext()
					.getInitParameter(START_PAGE_ATTRIBUTE);
			if (startPage != null) {
				try {
					context.getResponse().sendRedirect(startPage);
				} catch (IOException e) {
					throw new ChainException(e);
				}
			} else {
				chain.getCommands().clear();
				chain.proceed();
			}
		}
		String webPackage = context.getWebPackage();
		RequestScope requestScope = RequestScopeBuilder.build(requestURI,
				webPackage);

		if (requestScope != null) {
			context.setRequestScope(requestScope);
			chain.proceed();
		} else {
			try {
				context.getResponse().sendError(404);
			} catch (IOException e) {
				throw new ChainException(e);
			}
		}
	}

}
